package com.itwxz.forum.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import com.itwxz.common.utils.StringUtils;
import com.itwxz.common.utils.bean.BeanUtils;
import com.itwxz.common.utils.ip.AddressUtils;
import com.itwxz.common.utils.ip.IpUtils;
import com.itwxz.forum.domain.dto.CommentDto;
import com.itwxz.forum.domain.po.ForumCommentParent;
import com.itwxz.forum.domain.po.ForumPost;
import com.itwxz.forum.domain.vo.CommentChildVo;
import com.itwxz.forum.domain.vo.CommentParentVo;
import com.itwxz.forum.domain.vo.ForumUserInfoVo;
import com.itwxz.forum.mapper.ForumCommentChildMapper;
import com.itwxz.forum.mapper.ForumCommentParentMapper;
import com.itwxz.forum.service.ForumCommentParentService;
import com.itwxz.forum.service.ForumPostService;
import com.itwxz.forum.utils.SaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Admin
 * @description 针对表【forum_comment_parent(一级评论表)】的数据库操作Service实现
 * @createDate 2025-05-13 17:33:49
 */
@Service
@Transactional
public class ForumCommentParentServiceImpl extends ServiceImpl<ForumCommentParentMapper, ForumCommentParent>
        implements ForumCommentParentService {

    @Autowired
    private ForumCommentParentMapper commentParentMapper;
    @Autowired
    private ForumCommentChildMapper commentChildMapper;
    @Autowired
    private ForumPostService postService;

    public IPage<CommentParentVo> getParentCommentsWithChild(Long postId, int pageNum, int pageSize) {
        // 1. 分页查询一级评论
        Page<ForumCommentParent> page = new Page<>(pageNum, pageSize);
        IPage<ForumCommentParent> parentPage = commentParentMapper.selectParentCommentsByPostId(page, postId);

        // 2. 获取父评论ID列表
        List<Long> parentIds = parentPage.getRecords().stream()
                .map(ForumCommentParent::getCommentId)
                .toList();

        // 3. 查询子评论，避免空列表导致SQL错误
        List<CommentChildVo> childList = new ArrayList<>();
        if (!parentIds.isEmpty()) {
            childList = commentChildMapper.selectAllChildByParentIds(parentIds);
        }

        // 4. 按父评论ID分组子评论
        Map<Long, List<CommentChildVo>> childMap = childList.stream()
                .collect(Collectors.groupingBy(CommentChildVo::getParentId));

        // 5. 组装结果
        List<CommentParentVo> voList = parentPage.getRecords().stream().map(parent -> {
            CommentParentVo vo = new CommentParentVo();
            BeanUtils.copyProperties(parent, vo);
            vo.setCommentChildVo(childMap.getOrDefault(parent.getCommentId(), new ArrayList<>()));
            return vo;
        }).toList();

        // 6. 返回分页结果
        Page<CommentParentVo> resultPage = new Page<>();
        resultPage.setCurrent(pageNum);
        resultPage.setSize(pageSize);
        resultPage.setTotal(parentPage.getTotal());
        resultPage.setRecords(voList);
        return resultPage;
    }

    @Override
    public SaResult addParentComment(CommentDto dto) {
        List<String> sensitiveWords = SensitiveWordHelper.findAll(dto.getContent());
        if (!sensitiveWords.isEmpty()) {
            return SaResult.error("评论含敏感词：" + String.join("，", sensitiveWords));
        }

        ForumCommentParent comment = BeanUtils.copyBean(dto, ForumCommentParent.class);
        comment.setUserId(StpUtil.getLoginIdAsLong());

        comment.setCreateBy(SaUtils.getNickname());

        String ip = IpUtils.getIpAddr();
        comment.setIp(ip);
        comment.setLocation(AddressUtils.getRealAddressByIP(ip));

        save(comment);

        postService.incrementCommentCount(String.valueOf(comment.getPostId()));

        return SaResult.ok("评论成功");
    }

    @Override
    public SaResult deleteParentComment(String commentId) {
        ForumCommentParent parent = getById(commentId);
        if (parent == null) return SaResult.error("评论不存在");

        String userId = String.valueOf(parent.getUserId());

        if (!StpUtil.getLoginIdAsString().equals(userId))
            return SaResult.error("无权删除评论");

        removeById(commentId);

        postService.decrementCommentCount(String.valueOf(parent.getPostId()));

        return SaResult.ok("删除成功");
    }


}




